package com.lujieni.netty.c4;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;

import static io.netty.buffer.ByteBufUtil.appendPrettyHexDump;
import static io.netty.util.internal.StringUtil.NEWLINE;

// cut ByteBuf into small ByteBuf
public class TestSlice {

    public static void main(String[] args) {

        ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer(10);
        buffer.writeBytes(new byte[]{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'});

        // 在切片过程中没有发生数据复制
        ByteBuf b1 = buffer.slice(0, 5);
        b1.retain();
        ByteBuf b2 = buffer.slice(5, 5);
        b2.retain();

        b1.setByte(0, 'b');
        //b1.writeByte('x'); //child byteBuf can not insert, only can update because it share common memory with origin ByteBuf

        buffer.release();


        log(b1);
        log(b2);

        b1.release();
        b2.release();

    }

    public static void log(ByteBuf bb){
        int length = bb.readableBytes();
        int rows = length / 16 + (length % 15 == 0 ? 0 : 1 ) + 4;
        StringBuilder sb = new StringBuilder(rows * 80 * 2)
                .append("read index:").append(bb.readerIndex())
                .append(" write index:").append(bb.writerIndex())
                .append(" capacity:").append(bb.capacity())
                .append(NEWLINE);
        appendPrettyHexDump(sb, bb);
        System.out.println(sb.toString());
    }
}
